package com.abu.server.service.impl;

import com.abu.server.pojo.FileEntity;
import com.abu.server.mapper.FileMapper;
import com.abu.server.service.FileService;
import com.abu.server.utils.FileOperationTemplate;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 阿布
 * @since 2021-04-06
 */
@Slf4j
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {

    @Autowired
    private FileOperationTemplate fileOperationTemplate;

    @Autowired
    private FileMapper fileMapper;

    @Override
    public String uploadFile(MultipartFile file) {
//        1.获取原始文件名、文件类型以及大小（字节）
        String originalFilename = file.getOriginalFilename();
        String type = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        long size = file.getSize();
        if (StringUtils.isEmpty(type)) {
            type = "文件类型未知";
        }
//        2.上传文件到阿里OSS中并获取上传后的URL
        HashMap<String, String> paramMap = null;
        try {
//        3.调用工具类
            paramMap = this.fileOperationTemplate.toUpload(file);
        } catch (IOException e) {
            log.error("服务器上传失败:{}", e.getMessage());
        }
        String url = paramMap.get("url");
        String uuid = paramMap.get("uuid");
//        4.添加到数据库中
        FileEntity fileEntity = new FileEntity();
        fileEntity
                .setOriginalName(originalFilename)
                .setSize(size)
                .setType(type)
                .setUuid(uuid)
                .setAddress(url);
        int count = this.fileMapper.insert(fileEntity);
//        5.返回uuid
        return count == 1 ? uuid : null;
    }


    @Override
    public String getFileStream(String uuid) {
        String fileWriter = null;
        try {
//            调用工具类
            fileWriter = this.fileOperationTemplate.downLoadFile(uuid);
        } catch (IOException e) {
            log.error("下载失败：{}", e.getMessage());
        }
        return fileWriter;
    }


    @Override
    public FileEntity getMeta(String uuid) {
        return this.fileMapper.selectOne(new QueryWrapper<FileEntity>().eq("uuid", uuid));
    }
}
